package zlog

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"time"
)

const Field4LogId = "LogId"
const Field4Time = "timeStr"
const Field4URL = "requestUrl"
const Field4RequestForm = "requestForm"
const Field4RequestBody = "requestBody"
const Field4IP = "ip"
const Field4Token = "token"
const Field4Method = "method"

func getLogIdByCtx(ctx *gin.Context) string {
	if ctx == nil {
		return genLogId()
	}

	if logId := ctx.GetString(Field4LogId); logId != "" {
		return logId
	}

	return genLogId()
}

func genLogId() string {
	return fmt.Sprintf("%d", time.Now().UnixMilli())
}

func getMethodByCtx(ctx *gin.Context) string {
	if ctx.Request != nil && ctx.Request.Method != "" {
		return ctx.Request.Method
	}

	return ""
}

func getURLByCtx(ctx *gin.Context) string {
	if ctx.Request != nil && ctx.Request.RequestURI != "" {
		return ctx.Request.RequestURI
	}

	return ""
}

func getRequestFormByCtx(ctx *gin.Context) string {
	if ctx.Request != nil && ctx.Request.Form != nil {
		return ctx.Request.Form.Encode()
	}

	return ""
}

func getRequestBodyByCtx(ctx *gin.Context) string {
	if ctx.Request != nil && ctx.Request.Body != nil {
		var data []byte
		_, _ = ctx.Request.Body.Read(data)
		return string(data)
	}

	return ""
}
